<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表单标识" prop="formKey">
        <el-input
          v-model="queryParams.formKey"
          placeholder="请输入表单标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表单名称" prop="formName">
        <el-input
          v-model="queryParams.formName"
          placeholder="请输入表单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search"  @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['flowable:bpmForm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['flowable:bpmForm:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['flowable:bpmForm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['flowable:bpmForm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="bpmFormList" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="表单名称" align="center" prop="formName" />
      <el-table-column label="表单标识" align="center" prop="formKey" />
      <!--      <el-table-column label="状态" align="center" prop="status" />-->
      <el-table-column label="状态" align="center" key="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['flowable:bpmForm:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flowable:bpmForm:remove']"
          >删除</el-button>
          <el-button
            link
            type="primary"
            icon="Setting"
            @click="handleDesigner(scope.row)"
            v-hasPermi="['flowable:bpmForm:edit']"
          >设计</el-button>
          <el-button
            link
            type="primary"
            icon="View"
            @click="handelPreview(scope.row)"
            v-hasPermi="['flowable:bpmForm:edit']"
          >预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改流程表单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="bpmFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表单名称" prop="formName">
          <el-input v-model="form.formName" placeholder="请输入表单名称" />
        </el-form-item>

        <el-form-item label="表单标识" prop="formKey">
          <el-input v-model="form.formKey" placeholder="请输入表单标识" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="表单预览" v-model="previewOpen" width="500px" append-to-body>
      <FormCreate :rule="previewDetail.rule" :option="previewDetail.option" v-model="formData" v-model:api="fApi"></FormCreate>
    </el-dialog>
  </div>
</template>

<script setup name="bpmForm">

import {ref, reactive, onMounted, getCurrentInstance, computed, toRefs} from 'vue';
import { listBpmForm, getBpmForm, delBpmForm, addBpmForm, updateBpmForm } from "@/api/flowable/bpmForm";
import formCreate from "@form-create/element-ui";
import usePermissionStore from "@/store/modules/permission";
import {useRouter} from "vue-router";

const FormCreate = formCreate.$form();
const formData = ref({});
const options = ref({
  //表单提交事件
  onSubmit: function (formData) {
    alert(JSON.stringify(formData))
  }
});
const rule = ref([
  {
    type:'input',
    field:'goods_name',
    title:'商品名称',
    value:'form-create'
  },
  {
    type:'checkbox',
    field:'label',
    title:'标签',
    value:[0,1,2,3],
    options: [
      {label:'好用',value:0},
      {label:'快速',value:1},
      {label:'高效',value:2},
      {label:'全能',value:3},
    ]
  },
]);


// Data
const { proxy } = getCurrentInstance();
const router = useRouter();
const routes = computed(() => usePermissionStore().routes);

const fApi = ref({});
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const bpmFormList = ref([]);
const open = ref(false);
const title = ref("");
const previewOpen = ref(false);
const previewDetail = reactive({
  option: {},
  rule: []
});
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  formKey: undefined,
  formName: undefined,
  status: undefined,
  formOption: undefined,
  formFields: undefined,
});
const form = ref({});
const rules = reactive({
  id: [{ required: true, message: "主键ID不能为空", trigger: "blur" }],
  formKey: [{ required: true, message: "表单标识不能为空", trigger: "blur" }],
  formName: [{ required: true, message: "表单名称不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "change" }],
});

// Methods
const getList = () => {
  loading.value = true;
  listBpmForm(queryParams).then(response => {
    bpmFormList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    id: undefined,
    formKey: undefined,
    formName: undefined,
    status: undefined,
    formOption: undefined,
    formFields: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remark: undefined
  };
  proxy.resetForm("bpmFormRef");
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  proxy.resetForm("queryForm");
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加流程表单";
};

const handleUpdate = (row) => {
  loading.value = true;
  reset();
  const id = row.id || ids.value;
  getBpmForm(id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改流程表单";
  });
};

const submitForm = () => {
  proxy.$refs["bpmFormRef"].validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateBpmForm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addBpmForm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const idsToDelete = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除流程表单编号为"' + idsToDelete + '"的数据项？').then(() => {
    loading.value = true;
    return delBpmForm(idsToDelete);
  }).then(() => {
    loading.value = false;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {}).finally(() => {
    loading.value = false;
  });
};

const handleDesigner = (row) => {
  // proxy.$store.dispatch("tagsView/delView", $route);
  router.push({
    name: 'bpmFormDesigner',
    query: {
      id: row.id
    }
  });
};

const handelPreview = (row) => {
  previewDetail.rule = formCreate.parseJson(row.formFields);
  previewDetail.option = JSON.parse(row.formOption);
  previewOpen.value = true;
};

const handleStatusChange = (row) => {
  updateBpmForm(row);
};

const handleExport = () => {
  download('flowable/bpmForm/export', { ...queryParams }, `bpmForm_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
});
</script>
